<?php

namespace app\admin\controller;

use app\admin\model\AttrModel;
use app\admin\model\CommonModel;
use app\admin\model\SpecsModel;
use cmf\controller\AdminBaseController;
use think\Db;

//规格组管理
class SpecsController extends AdminBaseController
{

    //首页
    public function index(){
        $param = $this->request->param();
        $commonModel = new CommonModel();
        $list = Db::name('shop_category')
            ->where(function($query) use($param){
                if(isset($param['shop_id']) && $param['shop_id'] != '-1'){
                    $query->where('id',$param['shop_id']);
                }
            })
            ->field('*')
            ->order('id desc')
            ->paginate(null,false,['query'=>$param])
            ->each(function($item, $key) use($commonModel){
                $res_specs = $commonModel->selectWhereData('specs',['shop_id'=>$item['id']],'id,specs_name');
                $specs = array_column($res_specs,'specs_name');
                $item['specs_name'] = implode('，',$specs);
                return $item;
            });
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);

        //商城分类名称
        $this->assign('shop_category',$this->getShopCategory());
        //搜索商城分类
        $this->assign('shop_id',$param['shop_id']??-1);
        return $this->fetch();
    }

    //添加页码(暂时不用)
    public function add(){
        //商城分类
        $this->assign('shop_category',$this->getShopCategory());
        return $this->fetch();
    }

    //添加提交(暂时不用)
    public function save(){
        $data = $this->request->param();
        $result = $this->validate($data,'Specs.add');
        if($result !== true){
            $this->error($result);
        }

        //查询分类是否有规格
        $commonModel = new CommonModel();
        $is_specs = $commonModel->findWhereData('specs',['shop_id'=>$data['shop_id']],'id');
        if($is_specs){
            $this->error('该分类下已有规格，不可重复添加');
        }

        $specsModel = new SpecsModel();
        $attrModel = new AttrModel();
        Db::startTrans();
        foreach($data['specs_name'] as $s_key=>$value){
            if(!isset($data['attr_name'][$s_key]) && !empty($data['attr_name'][$s_key])){
                continue;
            }
            //组装规格组名称并写入
            $arr_specs = [];
            $arr_specs['shop_id'] = $data['shop_id'];
            $arr_specs['specs_name'] = $value;
            $res_specs = $specsModel->allowField(true)->create($arr_specs);
            $res1 = $res_specs->id;

            //组装规格项并写入
            $arr_attr = [];
            $res_attr = $data['attr_name'][$s_key];
            $key = 0;
            foreach($res_attr as $r_a_value){
                $key += 0;
                $r_a_value = $this->replace($r_a_value);
                if($r_a_value){
                    $arr_attr[$key]['shop_id'] = $data['shop_id'];
                    $arr_attr[$key]['specs_id'] = $res1;
                    $arr_attr[$key]['attr_name'] = $r_a_value;
                    $key++;
                }
            }
            $res2 = $attrModel->allowField(true)->saveAll($arr_attr);
        }
        if($res1 && $res2){
            Db::commit();
            $this->success('添加成功！', url('Specs/index'));
        }else{
            Db::rollback();
            $this->error('添加失败');
        }
    }

    //替换特殊字符
    public function replace($str){
        $search = array(" ","　","\n","\r","\t");
        $replace = array("","","","","");
        return str_replace($search, $replace, $str);
    }


    //编辑页码
    public function edit(){
        $id = $this->request->param('id');
        $post = Db::name('shop_category')
            ->where('id',$id)
            ->find();
        if($post){
            $specsModel = new SpecsModel();
            $res = $specsModel
                ->field('id,specs_name')
                ->with(['attrMany'=>function($query) use($post){
                    $query->where('shop_id',$post['id']);
                }])
                ->where('shop_id',$post['id'])
                ->select();
            $res->hidden(['attr_many'=>['specs_id']]);//隐藏无需字段
            $post['specs'] = $res->toArray();
        }
        $this->assign('post',$post);

        //商城分类
        $this->assign('shop_category',$this->getShopCategory());
        return $this->fetch();
    }

    //编辑提交
    public function update(){
        $data = $this->request->param();
        $result = $this->validate($data,'Specs.edit');
        if($result !== true){
            $this->error($result);
        }

        $specsModel = new SpecsModel();
        $attrModel = new AttrModel();
        $specs_count = count($data['specs_name']);
        if($specs_count > 3){
            $this->error('规格组最多三组');
        }

        Db::startTrans();
        foreach($data['specs_name'] as $s_key=>$value){
            if(!isset($data['attr_name'][$s_key]) && !empty($data['attr_name'][$s_key])){
                continue;
            }
            //组装规格组名称并写入
            if(isset($data['specs_ids'][$s_key])){
                //更新
                $specs_id = $data['specs_ids'][$s_key];
                $res1 = $specsModel->allowField(true)->save(['specs_name'=>$value],['id'=>$specs_id]);
            }else{
                //新增
                $arr_specs = [];
                $arr_specs['shop_id'] = $data['shop_id'];
                $arr_specs['specs_name'] = $value;
                $res1 = $specsModel->allowField(true)->create($arr_specs);
                $specs_id = $res1->id;
            }


            //组装规格属性并写入
            if(isset($data['attr_name'][$s_key])){
                $arr_attr = [];
                $res_attr = $data['attr_name'][$s_key];
                $key = 0;
                foreach($res_attr as $r_key=>$r_a_value){
                    $key += 0;
                    $r_a_value = $this->replace($r_a_value);
                    if($r_a_value){
                        if(isset($data['attr_ids'][$s_key][$r_key])){
                            //有attr_id，则更新
                            $arr_attr[$key]['id'] = $data['attr_ids'][$s_key][$r_key];
                        }else{
                            $arr_attr[$key]['shop_id'] = $data['shop_id'];
                            $arr_attr[$key]['specs_id'] = $specs_id;
                        }
                        $arr_attr[$key]['attr_name'] = $r_a_value;
                        $key++;
                    }
                }
                $res2 = $attrModel->allowField(true)->saveAll($arr_attr);
            }

            //查询规格关联
            $commonModel = new CommonModel();
            $relation = $commonModel->selectWhereData('shop_goods_relation',['shop_id'=>$data['shop_id']],'id,specs_attr');
            //判断删除的规格组，属性
            if(!empty($data['del_attr_ids'])){
                $del_attr_ids = explode(',',trim($data['del_attr_ids'],','));
                $res_attr = $this->getSpecsAttr('attr',['shop_id'=>$data['shop_id']],'id,attr_name','attr_name');
                foreach($relation as $r_value){
                    $specs_attr = json_decode($r_value['specs_attr'],true);
                    foreach ($specs_attr as $s_a_value){
                        if(in_array($s_a_value['attr_id'],$del_attr_ids)){
                            $this->error('商品已存在参数名称：'.$res_attr[$s_a_value['attr_id']]);
                        }
                    }
                }
                $attrModel->whereIn('id',$del_attr_ids)->delete();
            }

            if(!empty($data['del_specs_ids'])){
                $del_specs_ids = explode(',',trim($data['del_specs_ids'],','));
                $res_specs = $this->getSpecsAttr('specs',['shop_id'=>$data['shop_id']],'id,specs_name','specs_name');
                foreach($relation as $r_value){
                    $specs_attr = json_decode($r_value['specs_attr'],true);
                    foreach ($specs_attr as $s_a_value){
                        if(in_array($s_a_value['specs_id'],$del_specs_ids)){
                            $this->error('商品已存在规格组名称：'.$res_specs[$s_a_value['specs_id']]);
                        }
                    }
                }
                $specsModel->whereIn('id',$del_specs_ids)->delete();
                $attrModel->whereIn('specs_id',$del_specs_ids)->delete();
            }
        }
        if($res1 && $res2){
            Db::commit();
            $this->success('保存成功！', url('Specs/index'));
        }else{
            Db::rollback();
            $this->error('保存失败');
        }
    }

    //商城分类
    public function getShopCategory(){
        $commonModel = new CommonModel();
        $res = $commonModel->selectData('shop_category','id,shop_name');
        $arr = [];
        foreach($res as $value){
            $arr[$value['id']] = $value['shop_name'];
        }
        return $arr;
    }

    //规格属性
    public function getSpecsAttr($table,$where,$field,$field1){
        $commonModel = new CommonModel();
        $res = $commonModel->selectWhereData($table,$where,$field,$field1);
        $arr = [];
        foreach($res as $value){
            $arr[$value['id']] = $value[$field1];
        }
        return $arr;
    }
}
